import * as THREE from "three";
import { Particle } from "./Particle";

export class Tween<T extends number | THREE.Vector3 | THREE.Color> {
  times: number[] = [];
  values: T[] = [];
  loop: boolean = false;
  key: keyof Particle;
  enable = true;

  constructor(timeArray: number[], valueArray: T[], key: keyof Particle) {
    this.times = timeArray;
    this.values = valueArray;
    this.key = key;
  }

  lerp(t: number) {
    let i = 0;
    let n = this.times.length;
    while (i < n && t > this.times[i]) i++;
    if (i === 0) return this.values[0];
    if (i === n) return this.values[n - 1];
    let p = (t - this.times[i - 1]) / (this.times[i] - this.times[i - 1]);
    let result ;
    //  这里的问题在于，我只是判断数组第一个元素，如果要让ts知道，我应该把  this.values[i] this.values[i+1]都判断一下。 ts才知道
    if (typeof ( this.values[0] as THREE.Vector3).lerp === 'function')
      {result= (this.values[i - 1] as THREE.Vector3).clone().lerp(this.values[i] as THREE.Vector3, p);}
    else { result =(this.values[i - 1] as number) + p * (this.values[i] as number  -  (this.values[i - 1] as number));}
    return result
  }

  update(time: number, particles: Particle[] | Set<Particle>) {
    if (!this.key) return;

    for (let particle of particles) {
      if (typeof (particle[this.key] as THREE.Vector3).copy === 'function') {
        (particle[this.key]as THREE.Vector3).copy(this.lerp(particle.age));
      } else {
        particle[this.key] = this.lerp(particle.age);
      }
    }
  }
}